<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="100px">
      <el-form-item label="广告商" prop="advertiser">
        <el-input
          v-model="queryParams.advertiser"
          placeholder="请输入广告商"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同开始时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          clearable
          size="small"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择合同开始时间"
        />
      </el-form-item>
      <el-form-item label="合同结束时间" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          clearable
          size="small"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择合同结束时间"
        />
      </el-form-item>
      <el-form-item label="广告费" prop="cost">
        <el-input
          v-model="queryParams.cost"
          placeholder="请输入广告费"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['advert:resource:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['advert:resource:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['advert:resource:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['advert:resource:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="resourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="广告名" align="center" prop="name" />
      <el-table-column label="广告商" align="center" prop="advertiser" />
      <el-table-column label="合同开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告费" align="center" prop="cost" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <!--      <el-table-column label="类型" align="center" prop="type" :formatter="typeFormat" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['advert:resource:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['advert:resource:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改广告资源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="广告名" prop="name">
          <el-input v-model="form.name" placeholder="请输入广告名" />
        </el-form-item>
        <el-form-item label="广告商" prop="advertiser">
          <el-input v-model="form.advertiser" placeholder="请输入广告商" />
        </el-form-item>
        <el-form-item label="合同开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            clearable
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择合同开始时间"
          />
        </el-form-item>
        <el-form-item label="合同结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            clearable
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择合同结束时间"
          />
        </el-form-item>
        <el-form-item label="广告费" prop="cost">
          <el-input v-model="form.cost" placeholder="请输入广告费" />
        </el-form-item>
        <!--<el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" disabled>
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>-->
        <el-form-item label="广告语">
          <el-input v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="广告图片">
          <el-upload
            ref="upload"
            :limit="1"
            accept="image/png,image/gif,image/jpg,image/jpeg"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-success="successPicture"
            :on-exceed="exceedFile"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
            <div slot="tip" class="el-upload__tip">只能上传gif/jpg/jpeg/png文件，且不超过20MB</div>
          </el-upload>
        </el-form-item>
        <!--<el-form-item label="广告视频">
          <el-upload
            ref="upload"
            :limit="1"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取视频</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading">上传到服务器</el-button>
          </el-upload>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { delPicture,listResource, getResource, delResource, addResource, updateResource, exportResource } from '@/api/advert/resource'
import Editor from '@/components/Editor'
import { getToken } from '@/utils/auth'

export default {
  name: 'Resource',
  components: {
    Editor,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 广告资源表格数据
      resourceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 类型字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        advertiser: null,
        startTime: null,
        endTime: null,
        cost: null,
        status: null,
        content: null,
        type: null,
        pictureUrl: null,
        videoUrl: null,
        communityId: null
      },
      // 表单参数
      form: {
        id: null,
        name: null,
        advertiser: null,
        startTime: null,
        endTime: null,
        cost: null,
        status: '0',
        content: null,
        type: '0',
        pictureUrl: null,
        videoUrl: null,
        communityId: null
      },
      // 表单校验
      rules: {
      },
      // 上传图片
      upload: {
        url: process.env.VUE_APP_BASE_API + '/advert/resource/picture',
        headers: {
          Authorization: getToken()
        },
        fileList: []
      },
      limitSize: 20,
      // pictureBaseUrl: 'http://localhost:8090/img/',
      pictureBaseUrl: 'https://www.runze.site/img/',

    }
  },
  created() {
    this.getList()
    this.getDicts('ad_resource_status').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('ad_resource_type').then(response => {
      this.typeOptions = response.data
    })
  },
  methods: {
    /** 查询广告资源列表 */
    getList() {
      this.loading = true
      listResource(this.queryParams).then(response => {
        this.resourceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        advertiser: null,
        startTime: null,
        endTime: null,
        cost: null,
        status: '0',
        content: null,
        type: '0',
        pictureUrl: null,
        videoUrl: null,
        communityId: null
      }
      this.resetForm('form')
      this.upload.fileList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加广告资源'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getResource(id).then(response => {
        this.form = response.data
        const url = this.form.pictureUrl
        if (url != null && url !== 'kong') {
          const file = {
            url: url,
            name: url.substring(url.lastIndexOf('_') + 1)
          }
          this.upload.fileList.push(file)
        }
        this.open = true
        this.title = '修改广告资源'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateResource(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addResource(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除广告资源编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delResource(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有广告资源数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportResource(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    },
    /* 上传图片相关参数 */
    successPicture(res, file, fileList) {
      console.log(res)
      this.form.pictureUrl = this.pictureBaseUrl + res.data
    },
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择一张图片，当前共选择了 ${files.length + fileList.length} 张图片`
      })
    },
    handleBeforeUpload(file) {
      const uploadLimit = this.limitSize
      // const uploadTypes = ['jpg', 'png', 'doc', 'docx', 'xlsx', 'zip', 'rar', 'pdf']
      const uploadTypes = ['jpg', 'png', 'gif', 'jpeg']
      const filetype = file.name.replace(/.+\./, '')
      const isRightSize = (file.size || 0) / uploadLimit / 1024 / 1024 < uploadLimit
      if (!isRightSize) {
        this.$message.error('文件大小超过 ' + uploadLimit + 'MB')
        return false
      }

      if (uploadTypes.indexOf(filetype.toLowerCase()) === -1) {
        this.$message.warning({
          message: '请上传后缀名为jpg、png、gif、jpeg的附件'
        })
        return false
      }
      return true
    },
    handleRemove(file, fileList) {
      const name = file.url.substring(file.url.lastIndexOf('/') + 1)
      console.log(name)
      delPicture(name).then(res => {
        // 删除成功将表单中的url设置为空
        this.form.pictureUrl = 'kong'
      })
    }
  }
}
</script>
